var restify = require('restify');
var jwt = require('json-web-token');

var config = require('./config');
var core = require('./src/core');

var server = restify.createServer({
	name: 'ismartApi',
	version: '0.0.1'
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());

server.post('/ycapi/:component', function (req, res, next) {
	var component = req.params.component;
	var token = req.headers['i-access-token'];
	var body = req.body;

	if (typeof body == 'string') {
		body = JSON.parse(body);
	}
	console.log('--------------------- request --------------------');
	console.log('| component: ' + component);
	if (body) {
		console.log('| params: ' + JSON.stringify(body));
	}
	console.log('| token: ' + token);

	if (config.componentCheck(component)) {
		core.main(component, token, body, function (data) {
			console.log('-------------------------------------------------');
			res.send(data);
		});
	} else {
		var noFound = {ret: 401, msg: component + ' no found'};
		console.log('| response: ' + JSON.stringify(noFound));
		console.log('-------------------------------------------------');
		res.send(noFound);
	}

	return next();
});

server.listen(8080, function () {
	console.log('%s listening at %s', server.name, server.url);
});
